import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { message } from 'ant-design-vue'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    rolesAll: [],
    info: {},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_ROLES_All: (state, rolesAll) => {
      state.rolesAll = rolesAll
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        console.log('userInfo', userInfo)
        login(userInfo)
          .then((response) => {
            console.log('返回', response)
            if (response.code === 200) {
              const result = response.data
              storage.set(ACCESS_TOKEN, result.Authorization, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
              storage.set('User_Id', result.userId)
              commit('SET_TOKEN', result.Authorization)
              resolve()
            } else {
              message.error(response.msg)
            }
          })
          .catch((error) => {
            console.log('erros', error)
            reject(error)
          })
          .finally(() => {})
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const userId = storage.get('User_Id')
        // 请求后端获取用户信息 /api/user/info 只查询菜单权限，不查询按钮权限
        getInfo({ userId, permissionLevelType:2 })
          .then((response) => {
            const { data } = response
            if (data.menuResponseTree && data.menuResponseTree.length > 0) {
              console.log('data111', response)
              console.log(JSON.parse(JSON.stringify(data)), '  userInfo')
              commit('SET_ROLES', data.menuResponseTree)
              commit('SET_INFO', data)
              commit('SET_NAME', { name: data.nickName, welcome: data.roleName })
              commit('SET_AVATAR', data.avatar)
              resolve(response)
            } else {
              reject(new Error('getInfo: roles must be a non-null array !'))
            }
          })
          .catch((error) => {
            reject(error)
          })

        // 请求后端获取用户信息 /api/user/info 只查询菜单权限，不查询按钮权限
        // 查询类型：1-全部 2-排除permission_level != operate_permission
        getInfo({ userId, permissionLevelType:1 })
          .then((response) => {
            const { data } = response
            if (data.menuResponseTree && data.menuResponseTree.length > 0) {
              commit('SET_ROLES_All', data.menuResponseTree)
              resolve(response)
            } else {
              reject(new Error('getInfo: roles must be a non-null array !'))
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 刷新token
    // RefreshToken({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     refreshToken(state.token)
    //       .then((res) => {
    //         setExpiresIn(res.data);
    //         resolve();
    //       })
    //       .catch((error) => {
    //         reject(error);
    //       });
    //   });
    // },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        const userId = storage.get('User_Id')
        console.log(userId, '2userId', state)
        logout({ userId })
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            storage.remove(ACCESS_TOKEN)
            // removeToken()
            resolve()
          })
          .catch((err) => {
            console.log('logout fail:', err)
            reject(err)
          })
          .finally(() => {})
      })
    },
  },
}

export default user
